package com.kcht.sylyg08.service.impl;

import com.kcht.adp.common.config.ConfigurationValue;
import com.kcht.adp.common.log.Logger;
import com.kcht.sylyg08.service.IAsyncReportToMes;
import com.kcht.sylyg08.service.model.Upload;
import com.kcht.sylyg08.service.model.command;
import com.kcth.sylyg08.entity.CommandPer;

import javax.ejb.Stateless;
import javax.inject.Inject;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.Response;
import java.util.Deque;
import java.util.LinkedList;
import java.util.concurrent.Future;



/**
 * @author domjc
 * */
@SuppressWarnings("all")
@Stateless
@Deprecated
public class AsyncReportToMes implements IAsyncReportToMes {
    @Inject
    private Logger logger;

    private final Deque<Upload> futureQueue=new LinkedList<>();
    @Inject
    @ConfigurationValue
    private String MESURL;



    @Override
    public  void asyncSendReport(CommandPer commandPer) {
        int size = 200;
        /** 长度达到200，去除第一个元素 */
        if (futureQueue.size() >= size) {
            try{
                Upload upload = futureQueue.pollFirst();
                logger.info("取消上报任务--->"+upload.getUploadedData().getEpcCode());
                upload.getRespFuture().cancel(true);
                upload.getClient().close();
            }catch (Exception ignore){}
        }
        synchronized (futureQueue){
            Client client = ClientBuilder.newClient();
            Future<Response> futureResponse = client.target(MESURL).request().async().post(Entity.entity(mergePerRecordToCommand(commandPer), "application/json"));
            futureQueue.addLast(new Upload(commandPer,futureResponse,client));
            futureQueue.notifyAll();
        }
    }

    @Override
    public Deque<Upload> getAsyncFutures() {
        return futureQueue;
    }


    private command mergePerRecordToCommand(CommandPer commandPer){

        command cmd = new command();

        cmd.setEpcCode(commandPer.getEpcCode());
        cmd.setFlag(commandPer.getFlag());
        cmd.setDatetime(commandPer.getDatetime());
        cmd.setStaCode(commandPer.getStaCode());

        return cmd;
    }
}
